<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
        {{$store.state.count}}
        <ul>
            <li v-for="(item,ind) in $store.getters.saleList" :key="ind">{{item.name}} ---- {{item.price}}</li>
        </ul>
        
        <sum-number></sum-number>
        <reduce-number></reduce-number>
    </div>
    <script src="./vue.js"></script>
    <script src="./vuex.js"></script>
    <script>
        Vue.component('sum-number',{
            template:`
                <div>
                    <h1>当前的加数字是:{{$store.state.count}}</h1>
                    <button @click="add">加</button>
                </div>
            `,
            methods:{
                add(){
                    this.$store.commit('add',{num:1})
                }
            }
        })
        Vue.component('reduce-number',{
            template:`
                <div>
                    <h1>当前的减数字是:{{$store.state.count}}</h1>
                    <button @click="reduce">减</button>
                </div>
            `,
            methods:{
                reduce(){
                    this.$store.commit('reduce',{num:5})
                }
            }
        })

        let store = new Vuex.Store({
            state:{
                count:1,
                list:[]
            },
            mutations:{ //同步
                add(state,{num}){
                    console.log(this.state === state)
                    state.count += num ;
                },
                reduce(state,{num}){
                    state.count -= num;
                },
                changeList(state,arr){
                    state.list = arr;
                }
            },
            getters:{
                saleList(state){
                    state.list.forEach(item => {
                        item.price = `￥${item.price*0.5}`;
                    })
                    return state.list
                }
            },
            actions:{ //异步
                getData(context){  //
                    console.log(context)
                    
                    setTimeout(() => {
                        context.commit('changeList',[{name:'商品一',price:10}])
                    },2000)
                }
            }
        })


        let vm = new Vue({
            el:'#app',
            store
        })
    </script>
</body>
</html>